package com.study.controller;


import com.study.bean.entity.DormitoryAdmin;
import com.study.service.impl.AdminServiceImpl;
import com.study.util.CookieUtils;
import com.study.util.Result;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.study.util.JSONUtils.toJSON;

@WebServlet("/user")
public class UserController extends HttpServlet {
    private AdminServiceImpl adminService = new AdminServiceImpl();   //service层的唯一对象

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "login":
                login(req, resp);
                break;

            case "loginout":
                loginOut(req, resp);
                break;
            case "updatePwd":
                updatePwd(req, resp);
        }
    }

    private void updatePwd(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.updatePwd");
        HttpSession session = req.getSession();
        DormitoryAdmin admin = (DormitoryAdmin) session.getAttribute("admin");
        String oldPass = req.getParameter("oldPass");
        String newPass = req.getParameter("newPass");
        String RnewPass = req.getParameter("RnewPass");
        if (!admin.getPassword().equals(oldPass)) {
            toJSON(resp, Result.error("原密码错误"));
        } else if(!newPass.equals(RnewPass)){
            toJSON(resp, Result.error("两次密码输入不一致"));
        }
        else {

            int updatePwd = adminService.updatePwd(admin, newPass);
            if (updatePwd == 1){
                Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
                //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
                if (cookie != null) {
                    //设置Cookie的存活时间为0
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }
                session.removeAttribute("admin");
                toJSON(resp, Result.ok("修改成功,请重新登录"));
            }else {
                toJSON(resp, Result.error("修改失败"));
            }
        }
    }
    private void loginOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserController.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("admin");

        Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
        //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
        if (cookie != null) {
            //设置Cookie的存活时间为0
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
        toJSON(resp, Result.ok("退出成功"));
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.login");
        String name = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        String regexName = "^[a-zA-Z0-9_\\u4e00-\\u9fa5\\s·]+$";
        Pattern pattern = Pattern.compile(regexName);
        Matcher matcher = pattern.matcher(name);
        if (!matcher.find()) {
            toJSON(resp, Result.error("用户名不能有特殊字符"));
            return;
        }

        //先判断验证码是不是正确
        //1、验证码错误，返回一个验证码错误的提示
        //2、验证码正确，再验证验证码是不是正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            toJSON(resp, Result.error("验证码错误"));
            return;
        }

        DormitoryAdmin admin = adminService.login(name, password);
        /*if (user == null) {
            JSONUtils.toJSON(resp, Result.error("用户名或者密码错误"));
        } else {
            if (user.getStatus() == 0) {
                JSONUtils.toJSON(resp, Result.error("该用户已经禁用，请联系管理员"));
                return;
            }
            session.setAttribute("user", user);
            JSONUtils.toJSON(resp, Result.ok("登录成功"));

        }*/
        if (admin == null) {
            toJSON(resp, Result.error("用户名或者密码错误"));
            return;
        }

        //自动登录
        //判断有没有勾选自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)) {
            Cookie cookie = new Cookie("autoLogin", admin.getUsername() + "&" + admin.getPassword());
            //设置Cookie 的存活时间和绑定路径
            cookie.setMaxAge(60 * 60 * 24 * 7);//设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie，返回给浏览器
            resp.addCookie(cookie);
        }

        session.setAttribute("admin", admin);
        toJSON(resp, Result.ok("登录成功"));
    }
}
